#include "Sock.hpp"
#include <string>
#include <thread>
#include <unistd.h>

void Usage(std::string proc)
{
    std::cout << "Usage\n\t" << proc << " prot" << std::endl;
}

void Handler(int *pSock)
{
    int sock = *pSock;
    delete pSock;
#define MAX_SIZE 1024 * 10
    char buffer[MAX_SIZE];
    memset(buffer, 0, sizeof(buffer));

    ssize_t s = recv(sock, buffer, sizeof(buffer), 0);
    if (s > 0)
    {
        buffer[s] = 0;
        std::cout << buffer;

        std::string ret = "http/1.0 200 OK\n";
        ret += "Content-Type: text/plain\n"; //text/plain,正文是普通的文本
        ret += "\n";
        ret += "hello world";

        send(sock, ret.c_str(), ret.size(), 0);
    }
    close(sock);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }

    uint16_t port = static_cast<uint16_t>(atoi(argv[1]));
    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);

    //服务
    for (;;)
    {
        int new_sock = Sock::Accept(listen_sock);
        if (new_sock > 0)
        {
            int *pnew_sock = new int(new_sock);
            std::thread t(Handler, pnew_sock);
            t.detach();
        }
    }
    return 0;
}